package service

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/jinzhu/copier"
	"go-demo/mvc/model"
	"gorm.io/gorm"
)

type QuestionService struct {
	db *gorm.DB
}

func NewQuestionService(db *gorm.DB) *QuestionService {
	return &QuestionService{
		db: db,
	}
}

func (qs QuestionService) GetVoById(id int) (model.QuestionVo, error) {
	// 初始化变量
	var question model.Question
	var questionVo model.QuestionVo

	// 查询数据库
	result := qs.db.First(&question, id)
	if result.Error != nil {
		if errors.Is(result.Error, gorm.ErrRecordNotFound) {
			return questionVo, fmt.Errorf("question with ID %d not found", id)
		}
		return questionVo, fmt.Errorf("failed to query question: %w", result.Error)
	}

	// 字段映射 相当于beanUtil的copy 这里只拷贝 字段名 和 字段类型 一模一样的类型
	if err := copier.Copy(&questionVo, &question); err != nil {
		return questionVo, fmt.Errorf("failed to map question to questionVo: %w", err)
	}
	// 对 tags 字段做特殊处理
	err := json.Unmarshal([]byte(question.Tags), &questionVo.Tags)
	if err != nil {
		return model.QuestionVo{}, err
	}
	return questionVo, nil
}

func (qs *QuestionService) Page(request model.QuestionQueryParam) (model.PageResponse[model.QuestionVo], error) {
	var questions []model.Question

	// 构造查询条件
	query := qs.db.Model(&model.Question{})
	if request.UserId > 0 {
		query = query.Where("user_id = ?", request.UserId)
	}
	if len(request.Tags) > 0 {
		for _, tag := range request.Tags {
			query = query.Where("JSON_CONTAINS(tags, ?)", `"`+tag+`"`) // 确保包含所有标签
		}
	}
	if request.Content != "" {
		query = query.Where("content LIKE ?", request.Content+"%")
	}
	if request.Difficulty > 0 {
		query = query.Where("difficulty = ?", request.Difficulty)
	}
	if request.Title != "" {
		query = query.Where("title LIKE ?", request.Title+"%")
	}

	// 调用通用分页方法
	response, err := model.Page[model.Question](qs.db, query, request.PageRequest, &questions)
	if err != nil {
		return model.PageResponse[model.QuestionVo]{}, err
	}

	questionVos := make([]model.QuestionVo, len(questions))
	for i, question := range response.Data {
		questionVo, err := model.ConvertToQuestionVo(question)
		if err != nil {
			return model.PageResponse[model.QuestionVo]{}, err
		}
		questionVos[i] = questionVo
	}

	// 返回转换后的分页数据
	return model.PageResponse[model.QuestionVo]{
		Data:       questionVos,
		Page:       response.Page,
		PageSize:   response.PageSize,
		TotalPages: response.TotalPages,
		TotalCount: response.TotalCount,
	}, nil
}
